class Solver {

  ArrayList rules = new ArrayList();


  Solver() {
    String[] lines = null;
    String line;
    try {
      lines = loadStrings("rules.bin");
    }
    catch (NullPointerException e) {
    }

    for (int i = 0 ; i < lines.length ; i++) {
      line = lines[i];
      Rule rule = new Rule(line);
      rules.add(rule);
    }
  }

  Rule getRule(int i) {
    return (Rule)rules.get(i);
  }


  ArrayList crossing (ArrayList array1, ArrayList array2) {
    ArrayList result = new ArrayList();

    if (array1.size() < array2.size()) {
      for (int i = 0 ; i < array1.size() ; i++) {
        for (int j = 0 ; j < array2.size() ; j++) {
          if (array1.get(i).equals(array2.get(j))) {
            result.add(array1.get(i));
          }
        }
      }
    }
    else {
      for (int i = 0 ; i < array2.size() ; i++) {
        for (int j = 0 ; j < array1.size() ; j++) {
          if (array2.get(i).equals(array1.get(j))) {
            result.add(array2.get(i));
          }
        }
      }
    }
    return result;
  }

  ArrayList getCalcRule(String stat, ArrayList cond) {

    ArrayList result = new ArrayList();
    if (cond.size() == 0) {
      for (int i = 0; i < rules.size() ; i++) {
        Rule rule = (Rule)rules.get(i);
        if (stat.equals(rule.getCondition().get(0)) && rule.getCondition().size() == 1) {
          result = rule.getAction();
          
        }
      }
    }
    else if(stat.equals("a")){
      result.add("z");
    }
     else if(stat.equals("d")){
      result.add("y");
    }
    else {
      ArrayList need = new ArrayList();
      for (int i = 0 ; i < cond.size() ; i++) {
        ArrayList ok = new ArrayList();
        ok.add(stat);
        ok.add(cond.get(i));
       
        for (int j = 0 ; j < rules.size() ; j++) {
          Rule rule = (Rule)rules.get(j);

          if (rule.getCondition().equals(ok)) {
            need.add(rule);
          }
        }
      }
        Rule rule = (Rule)need.get(0);
        result = rule.getAction();
        for (int i = 1 ; i < need.size() ; i++) {
           rule = (Rule)need.get(i);
          result = crossing(rule.getAction(),result);
          
        }
        
        
    }

   // println(result);
    return result;
  }
}


